package com.mach.platform.controller;

import com.mach.platform.constants.CommonConstants;
import com.mach.platform.domain.PageVo;
import com.mach.platform.domain.Response;
import com.mach.platform.domain.iot.IotDev;
import com.mach.platform.domain.iot.IotSpace;
import com.mach.platform.repository.IotCollItemRepo;
import com.mach.platform.service.IotCollItemServiceImpl;
import com.mach.platform.service.IotDevServiceImpl;
import com.mach.platform.service.IotSpaceServiceImpl;
import com.mach.platform.utils.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @Description: 设备库控制器
 * @Package: com.mach.platform.controller
 * @time 2018/4/26 0026 15:21
 */
@Api(tags = {"空间接口"})
@RestController
@RequestMapping("/iot/space")
public class IotSpaceCtrl extends BaseCtrl<IotSpace> {

    @Autowired
    private IotSpaceServiceImpl iotSpaceService;

    @Autowired
    private IotDevServiceImpl iotDevService;

    @Autowired
    private IotCollItemServiceImpl collItemService;

    /**
     * 添加能源架构的程序(测试方法)
     * @return
     */
//    @PostMapping("/add")
//    public Response add() {
//        iotSpaceService.addEnergyStruc();
//        return Response.ok();
//    }

    /**
     * 删除空间，设备，参数(临时删除一些空间，设备数据，用于测试)
     *
     * @param ids
     */
    @PostMapping("/deleteSpaceDev")
    public Response deleteSpaceDev(@RequestBody Long[] ids) {
        boolean result = iotSpaceService.deleteSpaceDev(ids);
        return Response.ok(result);
    }


    /**
     * 查询母排有关的空间数据(车间和母线)
     *
     * @param type 查询类型 1.车间 2.母线
     * @param id   空间id
     * @return
     */
    @ApiOperation(value = "查询母排有关的空间数据(车间和母线)")
    @PostMapping("/busbarSpaces")
    public Response busbarSpaces(int type, Long id) {
        List<Map> result = iotSpaceService.busbarSpaces(type, id);
        return Response.ok(result);
    }


    /**
     * 查询母排设备的报警状态(有一个异常，就报警)
     *
     * @return
     */
    @ApiOperation(value = "查询母排设备的报警状态")
    @PostMapping("/workShopAlarmStatus")
    public Response workShopAlarmStatus() {
        int status = iotDevService.workShopAlarmStatus();
        return Response.ok(status);
    }


    /**
     * 查询空间下面的分页设备数据
     *
     * @param pageable 分页参数
     * @param id       空间id
     * @return
     */
    @ApiOperation(value = "查询空间下面的分页设备数据")
    @PostMapping("/pageIotDevBySpaceId")
    public Response pageIotDevBySpaceId(Pageable pageable, Long id) {
        PageVo result = iotSpaceService.pageIotDevBySpaceId(pageable, id);
        return Response.ok(result);
    }


    /**
     * 加载母线设备的实时数据
     *
     * @param id 设备id
     * @return
     */
    @ApiOperation(value = "加载母线设备的实时数据")
    @PostMapping("/loadIotDevCurData")
    public Response loadIotDevCurData(Long id) {
        Map result = iotDevService.loadIotDevCurData(id);
        return Response.ok(result);
    }


    /**
     * 母排测温温度走势
     *
     * @param id        设备id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    @ApiOperation(value = "母排测温温度走势")
    @PostMapping("/temperatureTrend")
    public Response temperatureTrend(Long id, String startTime, String endTime) {
        Map result = iotDevService.temperatureTrend(id, startTime, endTime);
        return Response.ok(result);
    }


    /**
     * 下载母线设备曲线走势数据
     *
     * @param id 设备id
     */
    @ApiOperation(value = "下载母线设备曲线走势数据")
    @PostMapping("/downBusDevData")
    public void downBusDevData(HttpServletResponse response, Long id, String startTime, String endTime) throws IOException {
//		IotDev iotDev = iotDevService.getIotDevById(id);
        XSSFWorkbook workbook = iotDevService.downBusDevData(id, startTime, endTime);
        // Excel下载的相关配置
        response.setHeader("Content-Disposition", "attachment; filename=温度曲线数据.xlsx");
        response.setContentType("application/vnd.ms-excel; charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }


    /**
     * 查询母线报警温度参数数据
     *
     * @param id 设备id
     * @return
     */
    @ApiOperation(value = "查询母线报警温度参数数据")
    @PostMapping("/alarmParams")
    public Response alarmParams(Long id) {
        Map result = iotDevService.alarmParams(id);
        return Response.ok(result);
    }


    /**
     * 母线报警温度设置
     *
     * @param params 设置参数
     * @return
     */
    @ApiOperation(value = "母线报警温度设置")
    @PostMapping(value = "/alarmSystem", produces = "application/json")
    public Response alarmSystem(@RequestBody Map params) {
        boolean flag = iotDevService.alarmSystem(params);
        if (flag) {
            return Response.ok("修改参数成功");
        }
        return Response.error("修改参数失败");
    }


    /**
     * 查询母线设备类型的全部属性
     *
     * @return
     */
    @ApiOperation(value = "查询母线设备类型的全部属性")
    @PostMapping("/busDevItems")
    public Response busDevItems() {
        List<String> items = collItemService.busDevItems();
        return Response.ok(items);
    }


    /**
     * 通过设备名称/编号查询设备
     *
     * @param params 参数：设备名称/设备编号
     * @return
     */
    @ApiOperation(value = "通过设备名称/编号查询设备")
    @PostMapping(value = "/findIotDev", produces = "application/json")
    public Response findIotDev(@RequestBody Map params) {
        String nameSn = (String) params.get("nameSn");
        Map iotDev = iotDevService.findByNameNumber(nameSn);
        if (iotDev.size() != 0) {
            return Response.ok();
        }
        return Response.error("设备名称或者编号不存在");
    }


    /**
     * 母线设备诊断--系统情况
     *
     * @return
     */
    @ApiOperation(value = "母线设备诊断--系统情况")
    @PostMapping(value = "/systemDiagnosis", produces = "application/json")
    public Response systemDiagnosis() {
        boolean flag = iotDevService.systemDiagnosis();
        if (flag) {
            return Response.ok("系统正常");
        }
        return Response.error("系统异常");
    }


    /**
     * 母线设备诊断--网络情况
     *
     * @param params 参数：设备名称/设备编号
     * @return
     */
    @ApiOperation(value = "母线设备诊断--网络情况")
    @PostMapping(value = "/networkDiagnosis", produces = "application/json")
    public Response networkDiagnosis(@RequestBody Map params) {
        String nameSn = (String) params.get("nameSn");
        boolean flag = iotDevService.networkDiagnosis(nameSn);
        if (flag) {
            return Response.ok("网络正常");
        }
        return Response.error("网络异常");
    }


    /**
     * 母线设备诊断--在线情况
     *
     * @param params 参数：设备名称/设备编号
     * @return
     */
    @ApiOperation(value = "母线设备诊断--在线情况")
    @PostMapping(value = "/onlineDiagnosis", produces = "application/json")
    public Response onlineDiagnosis(@RequestBody Map params) {
        String nameSn = (String) params.get("nameSn");
        boolean flag = iotDevService.onlineDiagnosis(nameSn);
        if (flag) {
            return Response.ok("设备在线");
        }
        return Response.error("设备不在线");
    }


    /**
     * 母线设备诊断--数据情况
     *
     * @param params 参数：设备名称/设备编号
     * @return
     */
    @ApiOperation(value = "母线设备诊断--数据情况")
    @PostMapping(value = "/dataDiagnosis")
    public Response dataDiagnosis(@RequestBody Map params) {
        String nameSn = (String) params.get("nameSn");
        String item = (String) params.get("item");
        if ("全部".equals(item)) {
            List<Map> result = iotDevService.allDataDiagnosis(nameSn);
            return Response.ok(result);
        }
        List<Map> result = iotDevService.oneDataDiagnosis(nameSn, item);
        return Response.ok(result);
    }


    /**
     * -- @GetMapping(value = "/info/{id}")
     * -- @ApiOperation(value = "单个实体信息", notes = "接口备注：无", produces = "application/json")
     * 单个数据 的接口
     * -- @PathVariable(value = "id", required = true) Long id
     *
     * @param id 数据的id
     * @return Response
     */
    @ApiOperation(value = "查询单个实体", notes = "单实例数据查询", produces = "application/json")
    @GetMapping(value = "/info")
    @Override
    public Response info(Long id) {
        return Response.ok(iotSpaceService.info(id));
    }

    /**
     * --	@ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
     * -- @GetMapping(value = "/xxxs")
     * 获取列表数据
     * -- @PageableDefault(size = 25) Pageable pageable
     * -- @RequestParam Map params
     *
     * @param pageable 分页参数
     * @param params   其他参数
     * @return Response
     */
    @ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
    @GetMapping(value = "/list")
    @Override
    public Response list(@PageableDefault(size = 121212121) Pageable pageable, @RequestParam Map params) {

        Page<IotSpace> dbResult = iotSpaceService.list(pageable, params);

        return Response.ok(dbResult);
    }

    /**
     * -- @DeleteMapping("/del")
     * -- @ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
     * 删除数据
     * -- @RequestBody Long[] ids
     *
     * @param ids id的集合
     * @return Response
     */
    @ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
    @DeleteMapping("/del")
    @Override
    public Response delete(@RequestBody Long[] ids) {
        boolean flag = iotDevService.spaceDevHasDependency(ids);
        if (flag) {
            return Response.error("当前节点已有关联设备数据，不能删除！");
        }

        if (Arrays.asList(ids).contains(1L)) {
            return Response.error("不能删除顶级的数据！");
        }
        Integer nums = iotSpaceService.delete(ids);

        return Response.ok(nums);
    }

    /**
     * --@PostMapping("/save")
     * --	@ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
     * 保存一个 对象
     * --@RequestBody T t
     *
     * @param space 保存的实体
     * @return Response
     */
    @ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
    @PostMapping("/save")
    @Override
    public Response save(@RequestBody IotSpace space) {

        return Response.ok(iotSpaceService.save(space));
    }

    @ApiOperation(value = "保存2", notes = "接口备注：无", produces = "application/json")
    @PostMapping("/save2")
    public Response save2(@RequestBody IotSpace space, @RequestParam(required = false) Integer ifBornSons) {
        IotSpace dbResult = iotSpaceService.save2(space, ifBornSons);
        return Response.ok(dbResult);
    }

    /**
     * createCoolSystem  创建制冷系统
     *
     * @param space
     * @param config
     * @return
     */
    @ApiOperation(value = "创建制冷系统", notes = "接口备注：无", produces = "application/json")
    @PostMapping("/createCoolSystem")
    public Response createCoolSystem(@RequestBody IotSpace space, @RequestParam Map config) {

        if (config.get(CommonConstants.SPACE_COOLPUMP_NAME) == null || config.get(CommonConstants.SPACE_COLDPUMP_NAME) == null || config.get(CommonConstants.SPACE_COOLTOWER_NAME) == null || config.get(CommonConstants.SPACE_COOLPUMP_NAME) == null) {
            return Response.error("参数不足");
        }
        IotSpace dbResult = iotSpaceService.createCoolSystem(space, config);
        return Response.ok(dbResult);
    }

    /**
     * --@PutMapping("/upd")
     * --	@ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
     * 更新一个对象
     * --@RequestBody T t
     *
     * @param device 更新的实体
     * @return Response
     */
    @ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
    @PutMapping("/upd")
    @Override
    public Response update(@RequestBody IotSpace device) {

        return Response.ok(iotSpaceService.update(device));
    }

    /**
     * 空间----级联选择数据格式
     *
     * @return Response
     */
    @ApiOperation(value = "空间----级联选择数据格式", notes = "接口备注：无", produces = "application/json")
    @PostMapping("cas")
    public Response tree() {

        List<Map> treeDatas = iotSpaceService.spaceTreeDatas();

        return Response.ok(treeDatas);
    }

    /**
     * 空间----加载站房的选项数据
     *
     * @return Response
     */
    @ApiOperation(value = "加载站房的选项数据", notes = "接口备注：无", produces = "application/json")
    @PostMapping("stations")
    public Response loadStationSelectionDatas(@ApiParam(value = "父级id") Integer spaceId, @ApiParam(value = "加载类别 2 是工厂 5 是站房") Integer type, @ApiParam(value = "站房类型模糊查询") String stationName) {
        List<Map> dbResult = iotSpaceService.loadStationSelectionDatas(spaceId, type);
        return Response.ok(dbResult);
    }

    /**
     * 空间----加载站房的顶部菜单
     *
     * @return Response
     */
    @ApiOperation(value = "加载站房的选项数据", notes = "接口备注：无", produces = "application/json")
    @PostMapping("titles")
    public Response loadStationSelectionDatase(@ApiParam(value = "父级id") Integer spaceId, @ApiParam(value = "加载类别 100 是工艺监视 101 是工艺控制 102是工艺能效") Integer type) {
        List<Map> dbResult = iotSpaceService.loadStationSelectionDatass(spaceId, type);
        return Response.ok(dbResult);
    }

}
